package com.rabbitmq.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.demo.conf.RPCQueueConfig;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeoutException;

/**
 * RPC模式生产者
 *
 * @Author yi.cheng
 * @Date 2023-7-17 09:58
 **/
@RestController
public class RPCQueueProducer {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/api/rpc")
    public String sendRpcFindProcessingWordOrder(@RequestParam String request){
        CorrelationData correlationData = new CorrelationData();
        // 发送数据
        //请求结果
        String result = null;
        //设置消息唯一id
        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
        //直接发送message对象
        MessageProperties messageProperties = new MessageProperties();
        //过期时间10秒,也是为了减少消息挤压的可能
        messageProperties.setExpiration("10000");
        messageProperties.setCorrelationId(correlationId.getId());
        Message message = new Message(request.getBytes(), messageProperties);

        StopWatch stopWatch = new StopWatch();
        stopWatch.start("direct模式下rpc请求耗时");
        Message response = rabbitTemplate.sendAndReceive("direct", "direct", message, correlationId);
        stopWatch.stop();

        if (response != null) {
            result = new String(response.getBody());
        }

        return result;
    }

}
